package com.iflytek.iot.okhttp.utils;

import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author yu 2019/8/5.
 */
public class OkHttp3Utils {

    private static final Logger LOGGER = LoggerFactory.getLogger(OkHttp3Utils.class);

    /**
     * 异步get请求
     *
     * @param client
     * @param baseUrl
     * @param params
     * @param headersMap
     * @param callback
     */
    public static void doAsyncGet(OkHttpClient client, String baseUrl, Map<String, String> params,
                                  Map<String, String> headersMap, Callback callback) {
        String url = urlJoin(baseUrl, params);
        LOGGER.debug("OkHttp3 async get url:{}", url);
        Request request;
        if (Objects.isNull(headersMap) || headersMap.size() == 0) {
            request = new Request.Builder().url(url).build();
        } else {
            Headers headers = setHeaders(headersMap);
            request = new Request.Builder().url(url).headers(headers).build();
        }
        Call call = client.newCall(request);
        call.enqueue(callback);
    }


    /**
     * 异步post请求
     *
     * @param client
     * @param url
     * @param body
     * @param headersMap
     * @param callback
     */
    public static void doAsyncPost(OkHttpClient client, String url, RequestBody body, Map<String, String> headersMap, Callback callback) {
        Request request;
        if (Objects.isNull(headersMap) || headersMap.size() == 0) {
            request = new Request.Builder().post(body).url(url).build();
        } else {
            Headers headers = setHeaders(headersMap);
            request = new Request.Builder().post(body).url(url).headers(headers).build();
        }
        Call call = client.newCall(request);
        call.enqueue(callback);
    }

    /**
     * 设置请求头
     *
     * @param headersParams
     * @return
     */
    private static Headers setHeaders(Map<String, String> headersParams) {
        Headers headers;
        okhttp3.Headers.Builder headersBuilder = new okhttp3.Headers.Builder();
        if (Objects.nonNull(headersParams)) {
            Iterator<String> iterator = headersParams.keySet().iterator();
            String key;
            while (iterator.hasNext()) {
                key = iterator.next();
                headersBuilder.add(key, headersParams.get(key));
            }
        }
        headers = headersBuilder.build();
        return headers;
    }

    private static String urlJoin(String url, Map<String, String> params) {
        StringBuilder endUrl = new StringBuilder(url);
        if (Objects.isNull(params)) {
            return url;
        }
        boolean isFirst = true;
        Set<Map.Entry<String, String>> entrySet = params.entrySet();
        for (Map.Entry<String, String> entry : entrySet) {
            if (isFirst && !url.contains("?")) {
                isFirst = false;
                endUrl.append("?");
            } else {
                endUrl.append("&");
            }
            endUrl.append(entry.getKey());
            endUrl.append("=");
            endUrl.append(entry.getValue());
        }
        return endUrl.toString();
    }
}
